<template>
  <view class="nfc-page">
    <nav-bar left-text="NFC取件"></nav-bar>
    <bg-set background="#f2f3f7" />
    <view class="nfc-page__main f ai-fs">
      <template v-if="loading">
        <view class="nfc f fd-col ai-c">
          <image
            src="/static/image/home/nfc.gif"
            mode="widthFix"
            style="width: 100%"
          ></image>
          <view style="margin-top: 20rpx"
            ><text style="font-weight: 600; font-size: 40rpx"
              >请靠近包裹nfc标签以核对信息取件</text
            ></view
          >
        </view>
      </template>
      <template v-else-if="pickUpLoading">
        <view class="nfc f fd-col ai-c">
          <image
            src="/static/image/home/pickUp_animate.gif"
            mode="widthFix"
            style="width: 100%"
          ></image>
          <view style="margin-top: 20rpx"
            ><text style="font-weight: 600; font-size: 40rpx"
              >取件中...</text
            ></view
          >
        </view>
      </template>
      <template v-else-if="!pickUpLoading && pickUpSuccess">
        <view class="nfc f fd-col ai-c">
          <image
            src="/static/image/home/pickUp_success.gif"
            mode="widthFix"
            style="width: 100%"
          ></image>
          <view style="margin-top: 20rpx"
            ><text style="font-weight: 600; font-size: 40rpx"
              >取件成功</text
            ></view
          >
        </view>
      </template>
    </view>
  </view>
</template>

<script>
let NfcAdapter;
let NdefRecord;
let NdefMessage;
let readyRead = false;
let noNFC = false;
let techListsArray = [
  ["android.nfc.tech.IsoDep"],
  ["android.nfc.tech.NfcA"],
  ["android.nfc.tech.NfcB"],
  ["android.nfc.tech.NfcF"],
  ["android.nfc.tech.Nfcf"],
  ["android.nfc.tech.NfcV"],
  ["android.nfc.tech.NdefFormatable"],
  ["android.nfc.tech.MifareClassi"],
  ["android.nfc.tech.MifareUltralight"],
];
const package_TECH_DISCOVERED = "android.nfc.action.TECH_DISCOVERED";
import profileAPI from "/api/modules/profile";
export default {
  name: "nfc-page",
  data() {
    return {
      userName: "",
      userPhone: "",
      goodsName: "",
      loading: false,
      pickUpLoading: false, //正在取件状态
      success: false, //数据获取成功与否
      pickUpSuccess: false, //取件成功与否
      timer1: null,
      timer2: null,
    };
  },
  onLoad(option) {
    this.userName = option.userName;
    this.userPhone = option.userPhone;
    this.goodsName = option.goodsName;
  },
  onShow() {
    console.log("nfc页面show");
    // 赋初值
    this.loading = false;
    this.pickUpLoading = false;
    this.success = false;
    this.pickUpSuccess = false;

    this.listenNFCStatus();
    this.readData();
    this.polling();
  },
  methods: {
    listenNFCStatus() {
      this.loading = true;
      try {
        const that = this;
        let main = plus.android.runtimeMainActivity();
        let Intent = plus.android.importClass("android.content.Intent");
        let PendingIntent = plus.android.importClass(
          "android.app.PendingIntent"
        );
        let IntentFilter = plus.android.importClass(
          "android.content.IntentFilter"
        );
        NfcAdapter = plus.android.importClass("android.nfc.NfcAdapter");
        let nfcAdapter = NfcAdapter.getDefaultAdapter(main);

        if (nfcAdapter == null) {
          this.toast("设备不支持NFC！");
          noNFC = true;
          return;
        }

        if (!nfcAdapter.isEnabled()) {
          this.toast("请在系统设置中先启用NFC功能！");
          this.loading = false;
          noNFC = true;
          return;
        } else {
          noNFC = false;
        }

        let intent = new Intent(main, main.getClass());
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        let pendingIntent = PendingIntent.getActivity(main, 0, intent, 0);
        let ndef = new IntentFilter("android.nfc.action.TECH_DISCOVERED");
        ndef.addDataType("*/*");
        let intentFiltersArray = [ndef];

        plus.globalEvent.addEventListener("newintent", function () {
          console.log("newintent running");
          // 轮询调用 NFC
          that.timer1 = setTimeout(() => that.nfcRuning(), 1000);
        });
        plus.globalEvent.addEventListener("pause", function (e) {
          console.log("pause running");
          if (nfcAdapter) {
            //关闭前台调度系统
            //恢复默认状态
            nfcAdapter.disableForegroundDispatch(main);
          }
        });
        plus.globalEvent.addEventListener("resume", function (e) {
          console.log("resume running");
          if (nfcAdapter) {
            //开启前台调度系统
            // 优于所有其他NFC
            nfcAdapter.enableForegroundDispatch(
              main,
              pendingIntent,
              intentFiltersArray,
              techListsArray
            );
          }
        });
        nfcAdapter.enableForegroundDispatch(
          main,
          pendingIntent,
          intentFiltersArray,
          techListsArray
        );
      } catch (e) {
        console.error(e);
      }
    },
    nfcRuning() {
      NdefRecord = plus.android.importClass("android.nfc.NdefRecord");
      NdefMessage = plus.android.importClass("android.nfc.NdefMessage");
      let main = plus.android.runtimeMainActivity();
      let intent = main.getIntent();
      console.log("action type:" + intent.getAction());
      if (package_TECH_DISCOVERED == intent.getAction()) {
        if (readyRead) {
          this.read(intent);
          readyRead = false;
        }
      }
    },
    read(intent) {
      this.toast("请勿移开标签正在读取数据");
      // NFC id
      let bytesId = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
      let nfc_id = this.byteArrayToHexString(bytesId);
      console.log("nfc_id:", nfc_id);
      let rawmsgs = intent.getParcelableArrayExtra(
        "android.nfc.extra.NDEF_MESSAGES"
      );

      if (rawmsgs != null && rawmsgs.length > 0) {
        let records = rawmsgs[0].getRecords();
        let result = records[0].getPayload();
        let data = plus.android.newObject("java.lang.String", result);
        this.toast("NFC 数据：" + data.slice(3));
        console.log("NFC 数据：", data.slice(3));
        const userName = JSON.parse(data.slice(3)).userName;
        const userPhone = JSON.parse(data.slice(3)).userPhone;
        const goodsName = JSON.parse(data.slice(3)).goodsName;
        this.success = true;
        if (
          this.userName === userName &&
          this.userPhone === userPhone &&
          this.goodsName === goodsName
        ) {
          const params = { signForStatus: 1, userName, userPhone, goodsName };
          this.pickUpLoading = true;
          this.loading = false;
          profileAPI
            .updateSignForStatusAndSignForTime(params)
            .then((res) => {
              console.log(res);
              this.pickUpSuccess = true;
              uni.showToast({
                title: "取件成功",
                icon: "success",
                duration: 1000,
                position: "top",
              });
            })
            .catch((err) => {
              this.pickUpSuccess = false;
              this.toast("nfc取件失败");
              console.log(err);
            })
            .finally(() => {
              this.pickUpLoading = false;
              console.log(this.pickUpSuccess, this.loading, this.pickUpLoading);
            });
        } else {
          this.toast("nfc取件失败");
        }
      } else {
        this.toast("没有读取到数据");
      }
    },
    byteArrayToHexString(inarray) {
      // converts byte arrays to string
      let i, j, inn;
      let hex = [
        "0",
        "1",
        "2",
        "3",
        "4",
        "5",
        "6",
        "7",
        "8",
        "9",
        "A",
        "B",
        "C",
        "D",
        "E",
        "F",
      ];
      let out = "";

      for (j = 0; j < inarray.length; ++j) {
        inn = inarray[j] & 0xff;
        i = (inn >>> 4) & 0x0f;
        out += hex[i];
        i = inn & 0x0f;
        out += hex[i];
      }
      return out;
    },
    readData() {
      if (noNFC) {
        this.toast("请检查设备是否支持并开启 NFC 功能！");
        return;
      }
      // 轮询条件
      readyRead = true;
      this.toast("请将NFC标签靠近！");
    },
    toast(title) {
      uni.showToast({
        title,
        icon: "none",
        position: "top",
      });
    },
    polling() {
      this.timer2 = setInterval(() => {
        if (this.success) {
          clearTimeout(this.timer1);
          clearInterval(this.timer2);
          this.loading = false;
        }
      }, 100);
    },
  },
};
</script>
<style lang='scss' scoped>
.nfc-page {
  position: fixed;
  width: 100%;
  height: 100vh;
  &__main {
    width: 100%;
    height: calc(100% - 86rpx);
    box-sizing: border-box;
    background-color: #e9ebec;
    .nfc {
      width: 100%;
    }
  }
}
</style>